package com.rabbit.task.configure;

import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.rabbit.task.parser.ElasticJobConfParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 解析配置esjop
 *
 * @author: 顾志杰
 */
@Configuration
/**
 * 配置文件内必须配置 elastic.job.zookeeper.namespace 和 elastic.job.zookeeper.serverLists 否则不加载此配置文件
 */
@ConditionalOnProperty(prefix = "elastic.job.zookeeper",name = {"namespace","serverLists"},matchIfMissing = false)
@EnableConfigurationProperties(JobZookeeperProperties.class)
@Slf4j
public class JobParserAutoConfigurartion {


    /**
     * 配置zookeeper 注册中心
     * @param jobZookeeperProperties
     * @return
     */
    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter zookeeperRegistryCenter(JobZookeeperProperties jobZookeeperProperties){
        ZookeeperConfiguration zookeeperConfiguration = new ZookeeperConfiguration(
                jobZookeeperProperties.getServerLists(),
                jobZookeeperProperties.getNamespace()
        );
        zookeeperConfiguration.setBaseSleepTimeMilliseconds(jobZookeeperProperties.getBaseSleepTimeMilliseconds());
        zookeeperConfiguration.setMaxSleepTimeMilliseconds(jobZookeeperProperties.getMaxSleepTimeMilliseconds());
        zookeeperConfiguration.setConnectionTimeoutMilliseconds(jobZookeeperProperties.getConnectionTimeoutMilliseconds());
        zookeeperConfiguration.setSessionTimeoutMilliseconds(jobZookeeperProperties.getSessionTimeoutMilliseconds());
        zookeeperConfiguration.setMaxRetries(jobZookeeperProperties.getMaxRetries());
        zookeeperConfiguration.setDigest(jobZookeeperProperties.getDigest());
        log.info("初始化job注册中心配置成功，zkaddress : {},namespace : {}", jobZookeeperProperties.getServerLists(), jobZookeeperProperties.getNamespace());
        return new ZookeeperRegistryCenter(zookeeperConfiguration);
    }

    @Bean
    public ElasticJobConfParser elasticJobConfParser(JobZookeeperProperties jobZookeeperProperties, ZookeeperRegistryCenter zookeeperRegistryCenter){
        return new ElasticJobConfParser(jobZookeeperProperties,zookeeperRegistryCenter);
    }


}
